<script setup lang="ts">
import type { FormItemInstance } from 'element-plus'
import { Icon } from '@iconify/vue'
import { ref } from 'vue'

const { prop, save } = defineProps<{
  prop: string
  save: () => Promise<any>
}>()

const model = defineModel<string>()

const modifyFlag = ref(false)

const formItemRef = ref<FormItemInstance>()
async function onSave() {
  formItemRef.value?.validate('', async (valid) => {
    if (valid) {
      await save()
      modifyFlag.value = false
    }
  })
}

function cancel() {
  formItemRef.value?.resetField()
  modifyFlag.value = false
}
</script>

<template>
  <el-form-item
    v-if="modifyFlag"
    ref="formItemRef" :prop="prop" style="margin: 0;"
  >
    <slot>
      <el-input v-model="model" />
    </slot>
  </el-form-item>
  <div v-else>
    {{ model }}
  </div>
  <Icon v-if="!modifyFlag" icon="tdesign:edit-2" class="cursor-pointer text-active" @click="modifyFlag = true" />
  <Icon v-if="modifyFlag" icon="tdesign:check" class="cursor-pointer text-active" @click="onSave() " />
  <Icon v-if="modifyFlag" icon="tdesign:close" class="cursor-pointer" @click="cancel" />
</template>
